﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CropImage2Block
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {

        private int _inputImgWidth;

        public int InputImgWidth
        {
            get { return _inputImgWidth; }
            set
            {
                _inputImgWidth = value;
                NotifyOfPropertyChanged(() => InputImgWidth);
                NotifyOfPropertyChanged(() => Columns);
                NotifyOfPropertyChanged(() => TotalBlock);
            }
        }

        private int _inputImgHeight;

        public int InputImgHeight
        {
            get { return _inputImgHeight; }
            set
            {
                _inputImgHeight = value;
                NotifyOfPropertyChanged(() => InputImgHeight);
                NotifyOfPropertyChanged(() => Rows);
                NotifyOfPropertyChanged(() => TotalBlock);
            }
        }

        private int _cropImgWidth = 1024;

        public int CropImgWidth
        {
            get { return _cropImgWidth; }
            set
            {
                _cropImgWidth = value;
                NotifyOfPropertyChanged(() => CropImgWidth);
                NotifyOfPropertyChanged(() => Columns);
                NotifyOfPropertyChanged(() => TotalBlock);
            }
        }

        private int _cropImgHeight = 1024;

        public int CropImgHeight
        {
            get { return _cropImgHeight; }
            set
            {
                _cropImgHeight = value;
                NotifyOfPropertyChanged(() => CropImgHeight);
                NotifyOfPropertyChanged(() => Rows);
                NotifyOfPropertyChanged(() => TotalBlock);
            }
        }

        public int Columns => (int)Math.Ceiling((double)InputImgWidth / CropImgWidth);

        public int Rows => (int)Math.Ceiling((double)InputImgHeight / CropImgHeight);

        public int TotalBlock => Columns * Rows;

        private int _finishedBlock;

        public int FinishedBlock
        {
            get { return _finishedBlock; }
            set
            {
                _finishedBlock = value;
                NotifyOfPropertyChanged(() => FinishedBlock);
            }
        }

        private bool _isProcessing;

        public bool IsProcessing
        {
            get { return _isProcessing; }
            set
            {
                _isProcessing = value;
                NotifyOfPropertyChanged(() => IsProcessing);
            }
        }


        public MainWindow()
        {
            InitializeComponent();
        }


        private void CropImageAndOutput(string path, string outputDir, int width, int height)
        {
            var bigImg = new Bitmap(path);
            var totalWidth = bigImg.Width;
            var totalHeight = bigImg.Height;

            int column = (int)Math.Ceiling((double)totalWidth / width);
            int row = (int)Math.Ceiling((double)totalHeight / height);

            Bitmap bitmap = null;

            for (int y = 0; y < row; y++)
            {
                for (int x = 0; x < column; x++)
                {
                    var cropWidth = x * width + width > totalWidth ? totalWidth - x * width : width;
                    var cropHeight = y * height + height > totalHeight ? totalHeight - y * height : height;

                    bitmap = bigImg.Clone(new System.Drawing.Rectangle(x * width, y * height, cropWidth, cropHeight), System.Drawing.Imaging.PixelFormat.DontCare);
                    if (cropWidth != width || cropHeight != height)
                    {
                        var temp = new Bitmap(width, height);
                        var g = Graphics.FromImage(temp);
                        g.DrawImage(bitmap, 0, 0, cropWidth, cropHeight);

                        if (string.Equals(".png", _inputImgExt))
                        {
                            temp.Save($"{outputDir}\\{y},{x}.png", System.Drawing.Imaging.ImageFormat.Png);
                        }
                        else
                        {
                            temp.Save($"{outputDir}\\{y},{x}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        }

                        g.Dispose();
                        temp.Dispose();
                    }
                    else
                    {
                        if (string.Equals(".png", _inputImgExt))
                        {
                            bitmap.Save($"{outputDir}\\{y},{x}.png", System.Drawing.Imaging.ImageFormat.Png);
                        }
                        else
                        {
                            bitmap.Save($"{outputDir}\\{y},{x}.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                    }
                    FinishedBlock++;
                }
            }
            bitmap?.Dispose();

            bigImg.Dispose();
        }

        private string _outputDir;




        private void Button_Click(object sender, RoutedEventArgs e)
        {
            FinishedBlock = 0;
            IsProcessing = true;
            new Action(() =>
            {
                _outputDir = $@"output\{DateTime.Now.ToString("yyyy_MM_dd hh_mm_ss")}";
                Directory.CreateDirectory(_outputDir);
                CropImageAndOutput(InputImgPath, _outputDir, CropImgWidth, CropImgHeight);
            }).BeginInvoke(obj =>
            {
                IsProcessing = false;
                Process.Start("explorer", System.IO.Path.Combine(Environment.CurrentDirectory, _outputDir));
            }, null);

        }

        private string _inputImgPath;

        public string InputImgPath
        {
            get { return _inputImgPath; }
            set
            {
                _inputImgPath = value;
                NotifyOfPropertyChanged(() => InputImgPath);
            }
        }

        private string _inputImgExt => System.IO.Path.GetExtension(InputImgPath).ToLower();


        public void NotifyOfPropertyChanged<T>(Expression<Func<T>> expr)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(((MemberExpression)expr.Body).Member.Name));
        }

        public event PropertyChangedEventHandler PropertyChanged;

        private void Window_Drop(object sender, DragEventArgs e)
        {
            InputImgPath = null;
            var filter = new List<string>() { ".jpg", ".png", ".gif" };
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                var datas = e.Data.GetData(DataFormats.FileDrop) as string[];

                foreach (var path in datas)
                {
                    var ext = System.IO.Path.GetExtension(path).ToLower();
                    if (filter.Contains(ext))
                    {
                        InputImgPath = path;

                        var bigImg = new Bitmap(InputImgPath);
                        InputImgWidth = bigImg.Width;
                        InputImgHeight = bigImg.Height;
                        bigImg.Dispose();
                        break;
                    }
                }
            }

            if (InputImgPath == null)
            {
                MessageBox.Show($"只支持图片格式的文件 ({string.Join(",", filter)})");
            }

        }
    }
}
